<template>
    <div>
        <Card  :style="'background:'+color+';margin: 4%'" >
            <Row>
                <Col :xs="{ span: 24, offset: 0 }" :sm="{ span: 20, offset: 0 }"  :md="{ span: 18, offset: 1 }" :lg="{ span: 13, offset: 1 }">
                    <h2 style="text-align:center; font-size: 24px; margin-top: 10px;">修改信息</h2>
                    <Form ref="upUserForm" :model="upUserForm" :rules="rules" :label-width="80" style="margin-top: 40px">
                        <FormItem label="学号" prop="userId">
                            <Input v-model="upUserForm.userId" placeholder="请输入学号" disabled="disabled"></Input>
                        </FormItem>
                        <FormItem label="姓名" prop="name">
                            <Input v-model="upUserForm.name" placeholder="请输入姓名"></Input>
                        </FormItem>
                        <FormItem label="手机号" prop="mobile">
                            <Input v-model="upUserForm.mobile" placeholder="请输入手机号"></Input>
                        </FormItem>
                        <FormItem label="邮箱" prop="email">
                            <Input v-model="upUserForm.email" placeholder="请输入邮箱"></Input>
                        </FormItem>
                        <FormItem>
                            <Button type="primary" @click="addUserSubmit('upUserForm')">更新信息</Button>
                            <Button style="margin-left: 20px" @click="upPassModal=true">修改密码</Button>
                        </FormItem>
                    </Form>
                    <Modal v-model="upPassModal"
                        title="修改密码">
                        <Form ref="upPassForm" :model="upPassForm" :rules="passRules" :label-width="80" style="margin-top: 20px">
                            <FormItem label="原密码" prop="oldPassword">
                                <Input  type="password" v-model="upPassForm.oldPassword" placeholder="请输入原密码" password></Input>
                            </FormItem>
                            <FormItem label="新密码" prop="password">
                                <Input type="password" v-model="upPassForm.password" placeholder="请输入新密码" password></Input>
                            </FormItem>
                            <FormItem label="确认密码" prop="checkPass">
                                <Input type="password" v-model="upPassForm.checkPass" placeholder="请确认新密码" password></Input>
                            </FormItem>
                        </Form>
                        <div slot="footer">
                            <Button type="primary" @click="upPass">提交</Button>
                            <Button  @click="upPassModal=false">取消</Button>
                        </div>
                    </Modal>
                </Col>
            </Row>
        </Card>
    </div>
</template>


<script>
    import cookie from 'js-cookie'
    import loginApi from '@/api/login'

    export default {
        name: "UpUserInfo",
        data(){
            var validateRealname = (rule, value, callback) => {
                if (Number.isFinite(value)) {
                    callback(new Error('请输入合法的姓名!'));
                }
                else if(value.length<2||value.length>20){
                    callback(new Error('请输入合法的姓名!'));
                }
                else {
                    callback();
                }
            };
            var validateNumber = (rule, value, callback) => {
                //使用正则表达式验证手机号
                if (!(/^1[3456789]\d{9}$/.test(value))){
                    callback(new Error('请输入合法的手机号!'));
                }
                else {
                    callback();
                }
            };
            var validateOldPass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入原密码'));
                } else {
                    // let user=JSON.parse(window.localStorage.getItem('loginUser'));
                    // TODO
                    if (this.upPassForm.checkPass !== '') {
                        this.$refs.upPassForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入新密码'));
                } else {
                    if (this.upPassForm.checkPass !== '') {
                        this.$refs.upPassForm.validateField('checkPass');
                    }
                    if(value.length<6||value.length>14){
                        callback(new Error('密码长度在6-14个字符之间'));
                    }
                    if(value===this.upPassForm.oldPass){
                        callback(new Error('新密码不能与原密码一致'));
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入新密码'));
                } else if (value !== this.upPassForm.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return{
                user:{},
                upUserForm:{
                    userId:'000000',
                    name:'test',
                    mobile:'phone',
                    email:'email',
                    password:'password'
                },
                token:{token:'000000'},
                rules: {
                    userId: [
                        { required: true, message: '请输入学号', trigger: 'blur' },
                    ],
                    name:[
                        { required: true, message: '请输入姓名', trigger: 'blur' },
                        { validator: validateRealname, message: '请输入真实姓名',trigger: 'blur' }
                    ],
                    mobile:[
                        { validator: validateNumber, trigger:'blur' }
                    ],
                    email:[
                        { type: 'email', message: '请输入合法的邮箱地址', trigger: 'blur'}
                    ]
                },
                upPassModal:false,
                upPassForm:{
                    oldPassword:'',
                    password:'',
                    checkPass:''
                },
                passRules:{
                    oldPassword: [
                        { validator: validateOldPass, trigger: 'blur' }
                    ],
                    password: [
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    checkPass: [
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                },
                color:'white'
            }
        },
        methods:{
            addUserSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        loginApi.changeMemberInfo(this.upUserForm).then(response => {
                            console.log('addUser:', response.data)
                            if(response.data.success){
                                cookie.set('userInfo', this.upUserForm, {domain: 'localhost'})
                                this.$router.push({path:'/info/stuInfo'})
                            }
                            else{
                                this.$Message.error('信息填写有误!');
                            }
                        })
                    } else {
                        this.$Message.error('信息填写有误!');
                    }
                })
            },
            handleSuccess:function (response, file, fileList) {
                if(response.data.result){
                    this.$Message.success('上传成功');
                }else {
                    this.$Message.error('上传失败');
                }
                let newUser=JSON.stringify(response.data.newUser);
                // window.localStorage.setItem('loginUser',newUser)
                // window.location.reload()
            },
            handleFormatError (file) {
                this.$Message.warning('请上传JPEG/JPG/PNG格式图片');
            },
            handleMaxSize (file) {
                this.$Message.warning('文件大小不能超过2m');
            },
            handleError(){
                this.$Message.warning('上传失败');
            },
            upPass:function () {
                this.$refs['upPassForm'].validate((valid) => {   //validate接受回调函数，为验证结果true或者false
                    if (valid) {
                        loginApi.changeStuPass(this.upPassForm).then(response => {
                            if(response.data.success){
                                this.$Message.success('修改成功');
                                this.$router.push({path:'/info/stuInfo'})
                            }
                            else{
                                this.$Message.warning('修改失败，原密码错误');
                                this.upPassForm.password = ''
                                this.upPassForm.oldPassword = ''
                                this.upPassForm.checkPass = ''
                            }
                        })
                        // let user = JSON.parse(window.localStorage.getItem('loginUser'));
                        // user.password = this.upPassForm.password;
                        // let newUser=this.$qs.stringify(user);
                        // this.$axios.post('/user/updateUser',newUser,
                        //     {
                        //         headers:{'token':window.localStorage.getItem('token')}
                        //     })
                        //     .then(res=>{
                        //         if(res.data.data.result){
                        //             this.$Message.success("修改成功,请重新登录");
                        //             window.localStorage.clear();
                        //             sessionStorage.clear();
                        //             this.$router.push('/login');
                        //         }else {
                        //             this.$Message.error('修改失败')
                        //         }
                        //     }).catch(err=>{
                        //    console.log(err)
                        // });
                        console.log('upPass success')
                    }else {
                      this.$Message.error('请完善信息!');
                        return false;
                    }
                });
            },
            getUserInfo: function() {
                //从cookie获取用户信息
                var userStr = cookie.get('userInfo')
                // 把字符串转换json对象(js对象)
                if(userStr) {
                    this.upUserForm = JSON.parse(userStr)
                }
            }
        },
        created(){
            this.getUserInfo()
        }
    }
</script>